package org.gl.training.planner.dao;

import java.util.Date;
import java.util.List;

import org.gl.training.planner.model.DailyPlan;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository(value = "dailyPlanDao")
public class DailyPlanDaoImpl extends HibernateDaoSupport implements
		DailyPlanDao {

	@Autowired
	public void init(SessionFactory factory) {
		setSessionFactory(factory);
	}

	@SuppressWarnings("unchecked")
	@Override
	public DailyPlan getDailyPlan(Integer userId, Date date) {
		List<DailyPlan> dailyPlanList = getHibernateTemplate()
				.find("from DailyPlan dp where dp.user.id=? and dp.date=?",
						userId, date);
		if (dailyPlanList.size() > 1) {
			throw new IllegalStateException("Received more then one DailyPlan");
		}
		if (dailyPlanList.size() == 1) {
			return dailyPlanList.get(0);
		}
		return null;
	}

}
